package ee.serge.client.content.cp;

import java.util.List;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import ee.serge.client.AlertBox;
import ee.serge.client.Move;
import ee.serge.service.Service;
import ee.serge.shared.Admin;
import ee.serge.util.AdminContent;
import ee.serge.util.ClickLabel;
import ee.serge.util.SimpleCallback;
import ee.serge.util.URLData;
import ee.serge.util.bootstrap.BButton;
import ee.serge.util.bootstrap.BButtonBar;
import ee.serge.util.bootstrap.BTable;

public class AccountsContent extends AdminContent {

   private static final String NAME = "cp/accounts";
   
   public static String getName() {
      return NAME;
   }
   
   public static URLData getURLData() {
      URLData data = new URLData();
      data.setName(NAME);
      return data;
   }
   
   public static void show() {
      Service.getControlPanelService().getAccountList(new SimpleCallback<List<Admin>>() {

         @Override
         public void success(List<Admin> result) {
            Move.get().setContent(new AccountsContent(result));
         }
      });
   }
   
   public AccountsContent(List<Admin> result) {
      makePanel(result);
   }
   
   private void makePanel(List<Admin> admins) {
      setHeader("Accounts", "Add and remove");
	  String[] headers = {"#", "Username", "Name", "Email", ""};
	  BTable grid = new BTable(admins.size(), headers, BTable.ZEBRA_STRIPED);
	  for (int i = 0; i < admins.size(); i++) {
	     Admin admin = admins.get(i);
      	 grid.setText(i, 0, String.valueOf(i + 1));
      	 grid.setText(i, 1, admin.getUsername());
      	 grid.setText(i, 2, admin.getName());
      	 grid.setText(i, 3, admin.getEmail());
      	 grid.setWidget(i, 4, new ClickLabel("Remove", new RemoveAccountHandler(admin.getUsername())));
	  }
	  
	  add(grid);
	  BButtonBar buttonBar = new BButtonBar();
	  buttonBar.add(new BButton("Add account", BButton.PRIMARY, new ClickHandler() {
	
		@Override
		public void onClick(ClickEvent event) {
			AccountAddPopup.showAdd();
		}
	  }));
	  add(buttonBar);
   }
   
   private class RemoveAccountHandler implements ClickHandler {
   	private String username;
   	public RemoveAccountHandler(String username) {
	      this.username = username;
      }
		@Override
      public void onClick(ClickEvent event) {
	      Service.getControlPanelService().removeAccount(username, new SimpleCallback<Void>() {

				@Override
            public void success(Void result) {
					Move.get().refresh();
	            AlertBox.showSuccess("Account removed");
            }
			});
      }
   	
   }
	
}
